package xyz.yq56.easytool.utils.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import xyz.yq56.easytool.utils.log.LogUtil;

/**
 * @author yiqiang
 */
@SuppressWarnings("unused")
public class JaXmlBeanUtil {

    private JaXmlBeanUtil() {
    }

    public static String toXml(Object obj) {
        return toXml(obj, "UTF-8");
    }

    /**
     * JavaBean转换成xml
     */
    public static String toXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            LogUtil.error("JaXmlBeanUtil.toXml Failed", e,null);
        }
        return result;
    }

    /**
     * xml转换成JavaBean
     */
    @SuppressWarnings("unchecked")
    public static <T> T toObject(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            LogUtil.error("JaXmlBeanUtil.toObject Failed", e,null);
        }
        return t;
    }

}
